<template>
  <div class="subscriptions-container">
    <el-card class="subscription-card">
      <template #header>
        <div class="card-header">
          <h2>我的订阅</h2>
          <el-tabs v-model="activeTab">
            <el-tab-pane label="文档订阅" name="documents"></el-tab-pane>
            <el-tab-pane label="分类订阅" name="categories"></el-tab-pane>
            <el-tab-pane label="标签订阅" name="tags"></el-tab-pane>
          </el-tabs>
        </div>
      </template>
      
      <div v-if="loading" class="loading-container">
        <el-skeleton :rows="6" animated />
      </div>
      
      <div v-else>
        <!-- 文档订阅 -->
        <div v-if="activeTab === 'documents'">
          <div v-if="documentSubscriptions.length === 0" class="empty-container">
            <el-empty description="暂无订阅的文档" />
          </div>
          <el-table v-else :data="documentSubscriptions" style="width: 100%">
            <el-table-column prop="title" label="文档标题" min-width="180"></el-table-column>
            <el-table-column prop="category" label="分类" width="120"></el-table-column>
            <el-table-column label="标签" width="180">
              <template #default="scope">
                <el-tag v-for="tag in scope.row.tags" :key="tag" size="small" effect="plain" style="margin-right: 5px">
                  {{ tag }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="subscribeTime" label="订阅时间" width="180">
              <template #default="scope">
                {{ new Date(scope.row.subscribeTime).toLocaleString() }}
              </template>
            </el-table-column>
            <el-table-column label="操作" width="150">
              <template #default="scope">
                <el-button size="small" plain @click="viewDocument(scope.row.id)">查看</el-button>
                <el-button 
                  size="small" 
                  type="danger" 
                  plain
                  @click="unsubscribeDocument(scope.row.id)"
                >
                  取消订阅
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
        
        <!-- 分类订阅 -->
        <div v-if="activeTab === 'categories'">
          <div v-if="categorySubscriptions.length === 0" class="empty-container">
            <el-empty description="暂无订阅的分类" />
          </div>
          <el-table v-else :data="categorySubscriptions" style="width: 100%">
            <el-table-column prop="name" label="分类名称" min-width="180"></el-table-column>
            <el-table-column prop="documentCount" label="文档数量" width="120"></el-table-column>
            <el-table-column prop="subscribeTime" label="订阅时间" width="180">
              <template #default="scope">
                {{ new Date(scope.row.subscribeTime).toLocaleString() }}
              </template>
            </el-table-column>
            <el-table-column label="操作" width="180">
              <template #default="scope">
                <el-button size="small" plain @click="browseCategory(scope.row.id)">浏览</el-button>
                <el-button 
                  size="small" 
                  type="danger" 
                  plain
                  @click="unsubscribeCategory(scope.row.id)"
                >
                  取消订阅
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
        
        <!-- 标签订阅 -->
        <div v-if="activeTab === 'tags'">
          <div v-if="tagSubscriptions.length === 0" class="empty-container">
            <el-empty description="暂无订阅的标签" />
          </div>
          <el-table v-else :data="tagSubscriptions" style="width: 100%">
            <el-table-column prop="name" label="标签名称" min-width="180"></el-table-column>
            <el-table-column prop="documentCount" label="文档数量" width="120"></el-table-column>
            <el-table-column prop="subscribeTime" label="订阅时间" width="180">
              <template #default="scope">
                {{ new Date(scope.row.subscribeTime).toLocaleString() }}
              </template>
            </el-table-column>
            <el-table-column label="操作" width="180">
              <template #default="scope">
                <el-button size="small" plain @click="browseTag(scope.row.id)">浏览</el-button>
                <el-button 
                  size="small" 
                  type="danger" 
                  plain
                  @click="unsubscribeTag(scope.row.id)"
                >
                  取消订阅
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
      
      <div class="pagination-container" v-if="total > 0">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50]"
          :total="total"
          layout="total, sizes, prev, pager, next"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'

const router = useRouter()

// 标签页状态
const activeTab = ref('documents')
const loading = ref(true)

// 分页状态
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 订阅数据
const documentSubscriptions = ref([])
const categorySubscriptions = ref([])
const tagSubscriptions = ref([])

// 监听标签页变化，切换时重新加载
watch(activeTab, () => {
  currentPage.value = 1
  fetchSubscriptions()
})

// 初始化
onMounted(() => {
  fetchSubscriptions()
})

// 获取订阅列表
async function fetchSubscriptions() {
  loading.value = true
  try {
    // 根据当前激活的标签页加载不同的数据
    if (activeTab.value === 'documents') {
      await fetchDocumentSubscriptions()
    } else if (activeTab.value === 'categories') {
      await fetchCategorySubscriptions()
    } else if (activeTab.value === 'tags') {
      await fetchTagSubscriptions()
    }
  } catch (error) {
    console.error('Failed to fetch subscriptions:', error)
    ElMessage.error('获取订阅数据失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

// 获取文档订阅
async function fetchDocumentSubscriptions() {
  try {
    // 这里替换为实际的API调用
    // const response = await axios.get('/api/subscriptions/documents', {
    //   params: { page: currentPage.value, size: pageSize.value }
    // })
    
    // 模拟数据
    await new Promise(resolve => setTimeout(resolve, 500))
    
    documentSubscriptions.value = Array.from({ length: 5 }, (_, i) => ({
      id: i + 1,
      title: `订阅文档 ${i + 1}`,
      category: '技术文档',
      tags: ['Vue', 'JavaScript'],
      subscribeTime: new Date().getTime() - Math.floor(Math.random() * 10000000)
    }))
    
    total.value = 15 // 模拟总数
  } catch (error) {
    console.error('Failed to fetch document subscriptions:', error)
    throw error
  }
}

// 获取分类订阅
async function fetchCategorySubscriptions() {
  try {
    // 这里替换为实际的API调用
    // const response = await axios.get('/api/subscriptions/categories', {
    //   params: { page: currentPage.value, size: pageSize.value }
    // })
    
    // 模拟数据
    await new Promise(resolve => setTimeout(resolve, 500))
    
    categorySubscriptions.value = Array.from({ length: 3 }, (_, i) => ({
      id: i + 1,
      name: `订阅分类 ${i + 1}`,
      documentCount: Math.floor(Math.random() * 20) + 1,
      subscribeTime: new Date().getTime() - Math.floor(Math.random() * 10000000)
    }))
    
    total.value = 3 // 模拟总数
  } catch (error) {
    console.error('Failed to fetch category subscriptions:', error)
    throw error
  }
}

// 获取标签订阅
async function fetchTagSubscriptions() {
  try {
    // 这里替换为实际的API调用
    // const response = await axios.get('/api/subscriptions/tags', {
    //   params: { page: currentPage.value, size: pageSize.value }
    // })
    
    // 模拟数据
    await new Promise(resolve => setTimeout(resolve, 500))
    
    tagSubscriptions.value = Array.from({ length: 4 }, (_, i) => ({
      id: i + 1,
      name: `订阅标签 ${i + 1}`,
      documentCount: Math.floor(Math.random() * 15) + 1,
      subscribeTime: new Date().getTime() - Math.floor(Math.random() * 10000000)
    }))
    
    total.value = 4 // 模拟总数
  } catch (error) {
    console.error('Failed to fetch tag subscriptions:', error)
    throw error
  }
}

// 查看文档
function viewDocument(id) {
  // 跳转到文档详情页
  ElMessage.info(`查看文档 ID: ${id}`)
}

// 浏览分类
function browseCategory(id) {
  // 跳转到首页并过滤该分类
  router.push({ path: '/', query: { category: id } })
}

// 浏览标签
function browseTag(id) {
  // 跳转到首页并过滤该标签
  router.push({ path: '/', query: { tag: id } })
}

// 取消文档订阅
async function unsubscribeDocument(id) {
  try {
    await ElMessageBox.confirm('确定要取消订阅此文档吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    // 这里替换为实际的API调用
    // await axios.delete(`/api/subscriptions/document/${id}`)
    
    // 模拟删除
    documentSubscriptions.value = documentSubscriptions.value.filter(doc => doc.id !== id)
    total.value--
    
    ElMessage.success('已取消订阅')
  } catch (error) {
    if (error !== 'cancel') {
      console.error('Failed to unsubscribe document:', error)
      ElMessage.error('操作失败，请稍后重试')
    }
  }
}

// 取消分类订阅
async function unsubscribeCategory(id) {
  try {
    await ElMessageBox.confirm('确定要取消订阅此分类吗？所有该分类下的文档更新将不再通知您。', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    // 这里替换为实际的API调用
    // await axios.delete(`/api/subscriptions/category/${id}`)
    
    // 模拟删除
    categorySubscriptions.value = categorySubscriptions.value.filter(cat => cat.id !== id)
    total.value--
    
    ElMessage.success('已取消订阅')
  } catch (error) {
    if (error !== 'cancel') {
      console.error('Failed to unsubscribe category:', error)
      ElMessage.error('操作失败，请稍后重试')
    }
  }
}

// 取消标签订阅
async function unsubscribeTag(id) {
  try {
    await ElMessageBox.confirm('确定要取消订阅此标签吗？所有带有该标签的文档更新将不再通知您。', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    // 这里替换为实际的API调用
    // await axios.delete(`/api/subscriptions/tag/${id}`)
    
    // 模拟删除
    tagSubscriptions.value = tagSubscriptions.value.filter(tag => tag.id !== id)
    total.value--
    
    ElMessage.success('已取消订阅')
  } catch (error) {
    if (error !== 'cancel') {
      console.error('Failed to unsubscribe tag:', error)
      ElMessage.error('操作失败，请稍后重试')
    }
  }
}

// 分页相关
function handleSizeChange(size) {
  pageSize.value = size
  fetchSubscriptions()
}

function handleCurrentChange(page) {
  currentPage.value = page
  fetchSubscriptions()
}
</script>

<style scoped>
.subscriptions-container {
  padding: 20px;
}

.subscription-card {
  width: 100%;
}

.card-header {
  display: flex;
  flex-direction: column;
}

.card-header h2 {
  margin: 0 0 10px 0;
}

.loading-container, 
.empty-container {
  padding: 40px 0;
  text-align: center;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}
</style> 